import { useRef, useState } from "react";
import StoTable from "../StoTable2";
import StoPaginator from "../StoPaginator";
import StoFilter, { FilterType } from "../StoFilter";

// import { getStudents } from "../../common/mockdata";
// const students = getStudents(10);

const filters = [
  {
    type: FilterType.TYPE_STRING,
    key: "name",
    placeholder: "请输入用户姓名",
  },

  {
    type: FilterType.TYPE_SELECT,
    key: "gender",
    placeholder: "性别",
    options: ["男", "女", "死变态"],
  },

  {
    type: FilterType.TYPE_NUMBER,
    key: "age",
    placeholder: "年龄",
  },
];

// const formatters = {
//   name: (key: string, item: any) => <a href={`/${item.id}`}>{item[key]}</a>,
//   avatar: (key: string, item: any) => (
//     <a href={`/${item.id}`}>
//       <img style={{ width: 40 }} src={`${item[key]}`} alt="" />
//     </a>
//   ),
// };

const pageSize = 10;

type TableXProps = {
  data: Record<string, any>[];
  width?: number;
  formatters?: Record<string, (key: string, item: any) => any>;
  sortables?: string[];
  pageSize?: number;
  onSelectedItemsChanged?: (items: Set<Record<string, any>>) => void;
};

/* 组合组件：自带筛选器和分页器的超级表格 */
const StoTableX: React.FC<TableXProps> = ({
  data: _data,
  width = 1000,
  formatters,
  sortables = ["id"],
  pageSize = 10,
  onSelectedItemsChanged,
}) => {
  const componentRef = useRef(null);

  const [data, setData] = useState(_data);

  const onDataFiltered = (newArr: Record<string, any>[]) => {
    console.log("onFiltered", newArr);

    (componentRef.current as any).turnToPage(1);
    setData(newArr);
  };

  return (
    <div>
      <StoFilter
        width={width}
        filters={filters}
        dataArr={_data}
        onDataFiltered={onDataFiltered}
        devMode={false}
      ></StoFilter>

      <StoTable
        ref={componentRef}
        arr={data}
        width={width}
        formatters={formatters}
        sortables={sortables}
        pageSize={pageSize}
        onSelectedItemsChanged={onSelectedItemsChanged}
      ></StoTable>

      <StoPaginator
        totalPages={Math.ceil(data.length / pageSize)}
        currentPage={1}
        onPageSelected={(page) => {
          console.log(page, "selected");
          (componentRef.current as any).turnToPage(page);
        }}
      ></StoPaginator>
    </div>
  );
};

export default StoTableX;
